package com.good.child.widgets.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.github.chrisbanes.photoview.OnPhotoTapListener;
import com.github.chrisbanes.photoview.PhotoView;
import com.good.child.R;
import com.good.child.widgets.ImageSaver;
import com.yimidida.library.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

/**
 * Create on: 2024/9/30
 * by Mr.Zhu
 * Description: 查看图片dialog
 */
public class PreviewDialog extends DialogFragment implements View.OnClickListener, OnPhotoTapListener {
    public static final String EXTRA_LIST_DATA = "EXTRA_LIST_DATA";
    private List<String> list;
    private int position;
    private ViewGroup.LayoutParams params;
    private ViewPager banner;
    private View view;
    private CardView cardVie;
    ImageView tvSave;//保存
    private String img;//当传进来只有一张图片时的路径
    private ProgressBar progressbar;
    private TextView tv_loading_text;
    private File currentFile;
    private boolean canSave = false;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = View.inflate(getActivity(), R.layout.activity_images_preview, null);
        dialog.setContentView(view);
        setData();
        return dialog;
    }

    public static void showDialog(FragmentManager fragmentManager, List<String> img, boolean canSave) {
        PreviewDialog previewDialog = new PreviewDialog();
        previewDialog.list = img;
        previewDialog.canSave = canSave;
        fragmentManager.beginTransaction().add(previewDialog, "").commitAllowingStateLoss();
    }

    public static void showDialog(FragmentManager fragmentManager, String img, boolean canSave) {
        PreviewDialog previewDialog = new PreviewDialog();
        previewDialog.img = img;
        previewDialog.canSave = canSave;
        fragmentManager.beginTransaction().add(previewDialog, "").commitAllowingStateLoss();
    }

    public static void showDialog(FragmentManager fragmentManager, int position, List<String> img, boolean canSave) {
        PreviewDialog previewDialog = new PreviewDialog();
        previewDialog.list = img;
        previewDialog.position = position;
        previewDialog.canSave = canSave;
        fragmentManager.beginTransaction().add(previewDialog, "").commitAllowingStateLoss();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    }

    private void setData() {
        banner = (ViewPager) view.findViewById(R.id.banner);
        view.findViewById(R.id.rl).setOnClickListener(this);
        cardVie = view.findViewById(R.id.cv_view);
        tvSave = view.findViewById(R.id.tv_save);
        progressbar = (ProgressBar) view.findViewById(R.id.progressbar);
        progressbar.setVisibility(View.VISIBLE);
        tv_loading_text = (TextView) view.findViewById(R.id.tv_loading_text);
        PreviewAdapter previewAdapter = new PreviewAdapter();
        if (!TextUtils.isEmpty(img)) {
            if (!URLUtil.isHttpUrl(img) && !URLUtil.isHttpsUrl(img)) {
                img = "file:///" + img;
            }
            previewAdapter.addImg(img);
            banner.setAdapter(previewAdapter);
            return;
        }
        if (list != null) {
            for (String url : list) {
                if (!URLUtil.isHttpsUrl(url) && !URLUtil.isHttpUrl(url) && !URLUtil.isFileUrl(url)) {
                    url = "file:///" + url;
                }
                previewAdapter.addImg(url);
            }
        }
        banner.setAdapter(previewAdapter);
        banner.setCurrentItem(position);
    }


    @Override
    public void onClick(View v) {
        dismiss();
    }

    public void setImgs(List<String> imgs) {
        list = imgs;
    }

    public void setImg(String img) {
        this.img = img;
    }

    @Override
    public void onPhotoTap(ImageView view, float x, float y) {
        dismiss();
    }

    private class PreviewAdapter extends PagerAdapter {
        private ArrayList<String> list = new ArrayList<>();

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        /**
         * 添加一张图片
         *
         * @param url
         */
        public void addImg(String url) {
            list.add(url);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @SuppressLint("CheckResult")
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            PhotoView imageView = new PhotoView(container.getContext());
            String url = list.get(position);
            imageView.setOnPhotoTapListener(PreviewDialog.this);
            if (canSave) {
                imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        cardVie.setVisibility(View.VISIBLE);
                        return true;
                    }
                });
                tvSave.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ImageSaver.saveImageToGallery(getActivity(), url, new ImageSaver.SaveImageListener() {
                            @Override
                            public void onSuccess() {
                                // 图片保存成功的处理逻辑
                                ToastUtil.showShort("保存成功");
                            }

                            @Override
                            public void onFail(String error) {
                                // 图片保存失败的处理逻辑
                            }
                        });
                    }
                });
            }
            container.addView(imageView);
            Glide.with(getActivity()).load(url).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Drawable> target, boolean b) {
                    progressbar.setVisibility(View.GONE);
                    tv_loading_text.setVisibility(View.VISIBLE);
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable drawable, Object o, Target<Drawable> target, DataSource dataSource, boolean b) {
                    tv_loading_text.setVisibility(View.GONE);
                    progressbar.setVisibility(View.GONE);
                    return false;
                }
            }).into(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

}
